import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import Redis from "ioredis";

import { DistributedLockClient } from "../src";
import { sleep } from "../src/utils";

let client: DistributedLockClient;

let count: number;
const add = async (): Promise<void> => {
  const lock = await client.acquireLock("abc", { note: "lock test" });
  console.log("-------------------------");
  console.log(new Date(), "- 获取成功");

  console.log(new Date(), "- 进入临界区");
  const temp = count;
  console.log(new Date(), "- count:", count);
  await sleep(1);
  count = temp + 1;

  console.log(new Date(), "- 临界区代码执行完毕, 即将释放锁");
  await lock.release();
  console.log(new Date(), "- 锁被释放");
  console.log("-------------------------\n");
};

(async (): Promise<void> => {
  /** 测试 redis 实现 */
  console.log("############# 测试 redis 实现 ##############");
  count = 0;
  const redis = new Redis(6379, "127.0.0.1");
  client = new DistributedLockClient(
    {
      redis,
      key_prefix: "lock",
      lease: 1000,
      heartbeat: 100,
      client_name: "instance-1"
    }
  );
  await Promise.all(Array.from({ length: 10 }, async () => add()));
  redis.disconnect();

  /** 测试 dynamodb 实现 */
  console.log("############# 测试 dynamodb 实现 ##############");
  count = 0;
  const dynamodb = new DynamoDBClient(
    { region: "ap-east-1" }
  );
  client = new DistributedLockClient(
    {
      dynamodb,
      table_name: "lock-test",
      lease: 1000,
      heartbeat: 100,
      client_name: "instance-1"
    }
  );
  await Promise.all(Array.from({ length: 10 }, async () => add()));
})();
